﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Interface;
using Phoenix.ReflectionExtensions;
using PServiceBus.Core.Logger;
using PServiceBus.Core.Runtime.Extensions;
using PServiceBus.WebSocket.RPC.DTO;
using PServiceBus.WebSocket.RPC.Runtime;
using PServiceBus.Core.Manager;

namespace PServiceBus.WebSocket.RPC {
    public static class RPCServer {

        private static IWebSocketServer _websocket;
        
        public static void Start(string host, int port, bool secured, string type, string cerfx = "") {
            _websocket = DynamicBroker.Broker[type].New() as IWebSocketServer;
            _websocket.Cerfx = cerfx;
            _websocket.OnMessage = (socket, message) =>
            {
                var command = message.FromJson<WebSocketRequest>();
                command.SocketID = socket.ID;
                command.ClientIpAddress = socket.ClientIpAddress;
                socket.Send(WebSocketMessageBus.Execute(command).ToJson());
            };
            _websocket.OnError = (socket, ex) => { };
            
            _websocket.OnClose = (socket) => {
                WebSocketMessageBus.Close(socket.ID);
            };
            WebSocketConnectionManager.Start();
            _websocket.Start(host, port, secured);
        }

        public static void Stop() {
            if (_websocket == null) return;
            WebSocketConnectionManager.Stop();
            _websocket.Close();
        }
    }
}
